package com.mingqi.enetconnected.view.Dialog.tree.indicator;


import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mingqi.enetconnected.R;
import com.mingqi.enetconnected.util.DeviceUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yaxi
 * @date 2018/9/18
 */
public class IndicatorContainer  extends LinearLayout {

    public static final String TAG = IndicatorContainer.class.getSimpleName();

    private LinearLayout mWraper;
    private Context mContext;

    private View mTrackView;

    /**
     * 追踪视图的位置
     */
    private int currentPosition;

    private LayoutParams mTrackParams;
    private List<Integer> mWidthList = new ArrayList<>();
    private int mInitLeftMargin;
    private int mInitRightMargin;

    private boolean hasTracker = false;

    public IndicatorContainer(Context context) {
        this(context,null);
    }

    public IndicatorContainer(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs , 0);
    }

    public IndicatorContainer(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        setOrientation(VERTICAL);
        setGravity(Gravity.CENTER_VERTICAL);
        if (mWraper == null) {
            // 初始化容器
            mWraper = new LinearLayout(mContext);
            mWraper.setOrientation(HORIZONTAL);

            LayoutParams params = new LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mInitLeftMargin = DeviceUtils.dp2px(mContext, 10);
            params.leftMargin = mInitLeftMargin;
            mInitRightMargin = DeviceUtils.dp2px(mContext, 10);
            params.rightMargin = mInitRightMargin;
            super.addView(mWraper, params);

        }
    }

    /**
     * 当操作Item的数量变化时，需要控制currentPosition
     * 这里需要判断逻辑是否必要
     * @param child
     */

    public void addItemView(final View child) {
        mWraper.addView(child);
        child.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int width = child.getWidth();
                mWidthList.add(width);

                if (!hasTracker){
                    View view = new View(getContext());
                    FrameLayout.LayoutParams viewParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 10);
                    view.setLayoutParams(viewParams);
                    view.setBackgroundColor(mContext.getResources().getColor(R.color.colorPrimary));

                    addTrackView(view);
                    hasTracker = true;
                }else{
                    Log.i(TAG, "onGlobalLayout: mWraper.getChildCount : " + mWraper.getChildCount());
                    smoothScrollToPosition(mWraper.getChildCount() - 1);
                }

                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1){
                    child.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }else{
                    child.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });
    }

    public void addItemView(final View child, final int index) {
        mWraper.addView(child,index);
        child.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int width = child.getWidth();
                mWidthList.add(index,width);

                if (!hasTracker){
                    View view = new View(getContext());
                    FrameLayout.LayoutParams viewParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 10);
                    view.setLayoutParams(viewParams);
                    view.setBackgroundColor(mContext.getResources().getColor(R.color.colorPrimary));

                    addTrackView(view);
                    hasTracker = true;
                }else{
                    Log.i(TAG, "onGlobalLayout: mWraper.getChildCount : " + mWraper.getChildCount());
                    smoothScrollToPosition(mWraper.getChildCount() - 1);
                }





                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1){
                    child.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }else{
                    child.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });
    }

    public void updateItemChild(final int position){
        final View childAt = mWraper.getChildAt(position);
        childAt.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int width = childAt.getWidth();
                mWidthList.set(position,width);

                    Log.i(TAG, "onGlobalLayout: mWraper.getChildCount : " + mWraper.getChildCount());
                    smoothScrollToPosition(position + 1);

                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1){
                    childAt.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }else{
                    childAt.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });
    }

    public void removeItemViews(int start,int count){
        mWraper.removeViews(start, count);
        for (int i = 0; i < count; i++) {
            mWidthList.remove(start);
            // TODO: 2018/10/22 check code
//            currentPosition --;
        }
    }

    public void setView(View child, int index){

    }

    /**
     * 添加底部跟踪指示器
     * @param tackView
     */
    public void addTrackView(View tackView) {
        if (tackView == null) {
            return;
        }
        mTrackView = tackView;
        super.addView(tackView);


        mTrackParams = (LayoutParams) mTrackView.getLayoutParams();
        mTrackParams.topMargin = DeviceUtils.dp2px(mContext,5);


        // 计算和指定指示器的宽度
        int width = mTrackParams.width;
        int firstWidth = mWidthList.get(0);
        if (width == ViewGroup.LayoutParams.MATCH_PARENT) {
            width = firstWidth;
        }
        if (width == ViewGroup.LayoutParams.WRAP_CONTENT){
            width = firstWidth / 2;
        }

        int firstLeftMargin = 0;

        // 计算跟踪的View初始左边距离
        if (width < firstWidth ) {
            firstLeftMargin = getLeftMargin(0,width);
        }

        mTrackParams.width = width;

        mTrackParams.leftMargin = firstLeftMargin + mInitLeftMargin;
        mTrackView.setLayoutParams(mTrackParams);
    }


    /**
     * 开启一个动画移动到当前位置
     */
    public void smoothScrollToPosition(int position) {
        if (mTrackView == null) {
            return;
        }

        if (position == currentPosition){
            return;
        }

        //将之前位置的文本字体恢复正常

        ((TextView) mWraper.getChildAt(currentPosition)).setTypeface(Typeface.DEFAULT);
        ((TextView) mWraper.getChildAt(position)).setTypeface(Typeface.DEFAULT_BOLD);

        //使最后一项不可见
//        if (position < mWraper.getChildCount() - 1){
//            mWraper.getChildAt(mWraper.getChildCount() - 1).setVisibility(GONE);
//        }else{
//            mWraper.getChildAt(mWraper.getChildCount() - 1).setVisibility(VISIBLE);
//        }

        // 获取当前指示器距左边的距离
        final int mCurrentLeftMargin = mTrackParams.leftMargin + mInitLeftMargin;
        // 计算出最终的距离
        final int finalLeftMargin = getDistance(position) + getLeftMargin(position,-2) + mInitLeftMargin;
        // 用于动画执行的事件
        final int distance = finalLeftMargin - mCurrentLeftMargin;

        // 利用属性动画不断的更新距离
        ObjectAnimator animator = ObjectAnimator.ofFloat(mTrackParams, "leftMargin",
                mCurrentLeftMargin, finalLeftMargin);


        final int currentWidth = mWidthList.get(currentPosition) / 2;
        final int finalWidth = mWidthList.get(position) / 2;

        ObjectAnimator widthAnimtor = ObjectAnimator.ofFloat(mTrackParams,"width",
                currentWidth, finalWidth);

//        // 添加动画监听不断的更新 leftMargin
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float currentLeftMargin = (float) animation.getAnimatedValue();
//                Log.i(TAG, "currentLeftMargin --> " + currentLeftMargin);
                mTrackParams.leftMargin = (int) currentLeftMargin;
                mTrackView.setLayoutParams(mTrackParams);
            }


        });

        widthAnimtor.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float currentWidth = (float) animation.getAnimatedValue();
//                Log.i(TAG, "currentWidth: " +currentWidth);
                mTrackParams.width = (int) currentWidth;
                mTrackView.setLayoutParams(mTrackParams);
            }
        });
        AnimatorSet set = new AnimatorSet();
        set.setInterpolator(new DecelerateInterpolator());
        set.setDuration(Math.abs(distance));
        set.playTogether(animator,widthAnimtor);
        set.start();

        currentPosition = position;
    }


    /**
     * 计算当前位置之前的所有view的宽度之和
     * @param position 视图位置
     * @return
     */
    public int getDistance(int position){
        int sum = 0;
        if (mWidthList.size() > position) {

            for (int i = 0; i < position; i++) {
                sum += mWidthList.get(i);
            }
        }
        return sum;
    }


    private int getLeftMargin(int position,int widthParams){
        if (widthParams == ViewGroup.LayoutParams.MATCH_PARENT){
            return 0;
        }else if (widthParams == ViewGroup.LayoutParams.WRAP_CONTENT){
            return mWidthList.get(position) / 4;
        }else{
            return (mWidthList.get(position) - widthParams) / 2;
        }
    }



    /**
     * 收集左右indicator项 的宽度
     */
    public void collectViewWidth(){
        int childCount = mWraper.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childAt = mWraper.getChildAt(i);
            int width = childAt.getWidth();
            mWidthList.add(width);
        }
    }


    public int getItemChildIndex(View child){
        int childCount = mWraper.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childAt = mWraper.getChildAt(i);
            if (child.equals(childAt)){
                return i;
            }
        }
        throw new NullPointerException("parent doesn't has this children!");
    }

}
